﻿using System.Data;
using DevExpress.Web.ASPxTreeList;
using DevExpress.Xpo.DB.Helpers;
using RR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Post : System.Web.UI.Page
{
    protected RegistRar regrar = new RegistRar();
    protected List<MENU> lst;
    DataSet ds = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack && !IsCallback)
        {
            // ASPxLabel4.Text = Page.Request.CurrentExecutionFilePath; // /SPR/post.aspx текущий путь
            //CreateDataSet();
        }
        else
        {
            //ds = (DataSet)Session["menuDataSet"];
        }
        //TreeList.DataSource = ds.Tables["GETMENURIGHT"];
       
    }
    protected void grd_post_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
    {
        if (e.NewValues["CODE"] == null)
            e.NewValues["CODE"] = regrar.Gen_id("WORKERSTATE_gen");
    }
    protected void menu_exp_ItemClick(object source, DevExpress.Web.ASPxMenu.MenuItemEventArgs e)
    {
        if (e.Item.Name == "btn_Excel")
            grd_export.WriteXlsxToResponse();
    }

    protected void TreeList_CustomDataCallback(object sender, DevExpress.Web.ASPxTreeList.TreeListCustomDataCallbackEventArgs e)
    {
        //object key = grd_post.GetRowValues(grd_post.FocusedRowIndex,"CODE");
        //foreach (var item in TreeList.Nodes)
        //{

        //}
        ////TreeListNode parentNode = null;

        //var query = (from m in regrar.MENU
        //             select m);
        //TreeList.SettingsSelection.Recursive = true;
        //TreeList.SettingsSelection.AllowSelectAll = true;
        //TreeList.SettingsSelection.Enabled = true;
        //TreeList.KeyFieldName = "ID";
        //TreeList.ParentFieldName = "ParentID";
        ////foreach (var item in query)
        ////{
        ////    if (item.PARENTID == 0)
        ////    {
        ////        parentNode = CreateNodeCore(item.ID, item.TEXT, Convert.ToInt32(item.PARENTID), null);
        ////    }
        ////    else
        ////    {
        ////        //parentNode.Expanded = true;
        ////        CreateNodeCore(item.ID, item.TEXT, Convert.ToInt32(item.PARENTID), parentNode);
        ////    }
        ////}
        //TreeList.DataSource = query.ToList();
        //TreeList.DataBind();
    }

    //TreeListNode CreateNodeCore(int key, string text, int parent, TreeListNode parentNode)
    //{
    //    var node = TreeList.AppendNode(key, parentNode);
    //    node["ID"] = key;
    //    node["TEXT"] = text;
    //    node["PARENTID"] = parent;
    //    node.Selected = true;
    //    return node;

    //}

    void CreateTreeList()
    {
        int role = Convert.ToInt32(grd_post.GetRowValues(grd_post.FocusedRowIndex, "CODE"));
        //FillTable(ds.Tables["MENUSET"]);
        dsMenuRight.SelectParameters["ROL"].DefaultValue = role.ToString();
        TreeList.DataBind();
        var query = (from m in regrar.MENURIGHT
                     where m.WORKERSTATE == role
                     select m);

        TreeList.UnselectAll();

        foreach (var item in query)
        {
            TreeListNode node = TreeList.FindNodeByFieldValue("ID", item.MENUID);
            if (node != null && !node.HasChildren)
                node.Selected = true;
        }
    }

    protected void cbPanel_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        int role = Convert.ToInt32(grd_post.GetRowValues(grd_post.FocusedRowIndex, "CODE"));
        dsMenuRight.SelectParameters["ROL"].DefaultValue = role.ToString();
        switch (e.Parameter)
        {
            case "select":
                CreateTreeList();
                break;
            case "clear":
              //  bt_save.Enabled = true;
                break;
            case "focusChange":
               // SetMenuVisible();
                break;
            case "saved":
                SaveNodes();
               // bt_save.Enabled = false;
                break;
            case "Add":
                SetStateAdd();
                break;
            case "Edit":
                SetStateEdit();
                break;
            case "Delete":
                SetStateDelete();
                break;
        }
    }

    protected void SetMenuVisible()
    {
        TreeListNode node = TreeList.FocusedNode;
      //  var n = node.GetValue("CODE");
      //  RightMenu.Visible = (n!="-1"); //& (Convert.ToInt32(node.GetValue("PARENTID")) != 0);
        
        //CreateTreeList();
    }

    protected void CreateDataSet()
    {
        ds = new DataSet();
        DataTable menuTable = new DataTable();
        menuTable.TableName = "MENUSET";
        menuTable.Columns.Add("ID", typeof(Int32));
        menuTable.Columns.Add("PARENTID", typeof(Int32));
        menuTable.Columns.Add("TEXT", typeof(string));
        menuTable.Columns.Add("ISADD", typeof(int));
        menuTable.Columns.Add("ISEDIT", typeof(int));
        menuTable.Columns.Add("ISDELETE", typeof(int));
        menuTable.PrimaryKey = new DataColumn[] { menuTable.Columns["ID"] };

        FillTable(menuTable);
        ds.Tables.Add(menuTable);
        Session["menuDataSet"] = ds;
    }

    protected void FillTable(DataTable menu)
    {
        int workerstate = Convert.ToInt32(grd_post.GetRowValues(grd_post.FocusedRowIndex, "CODE"));
        dsMenuRight.SelectParameters["ROL"].DefaultValue = workerstate.ToString();
    

        var query = from m in regrar.MENU
                    join ms in regrar.MENURIGHT on m.ID equals ms.MENUID
            //where ms.WORKERSTATE == workerstate
            select new
            {
                m.ID,
                m.PARENTID,
                m.TEXT,
                ms.ISADD,
                ms.ISEDIT,
                ms.ISDELETE
            };
        menu.Clear();
        foreach (var item in query)
        {
            var row = menu.NewRow();
            row["ID"] = item.ID;
            row["PARENTID"] = item.PARENTID;
            row["TEXT"] = item.TEXT;
            row["ISADD"] = item.ISADD;
            row["ISEDIT"] = item.ISEDIT;
            row["ISDELETE"] = item.ISDELETE;
            menu.Rows.Add(row);
        }
    }

    private void SetStateAdd()
    {
        TreeListNode node = TreeList.FocusedNode;
        int value = Convert.ToInt32(node.GetValue("ISADD"));
        int id = (int)node.GetValue("ID");
        int workerstate = Convert.ToInt32(grd_post.GetRowValues(grd_post.FocusedRowIndex, "CODE"));

        var query = (from m in regrar.MENURIGHT
                     where m.MENUID == id & m.WORKERSTATE == workerstate
                     select m).FirstOrDefault();
        if (query != null)
        {
            if (query.ISADD == 0)
            {
                query.ISADD = 1;
            }
            else
            {
                query.ISADD = 0;
            }
            regrar.SaveChanges();
        }
        //CreateTreeList();
        SetMenuVisible();
    }

    private void SetStateEdit()
    {
        TreeListNode node = TreeList.FocusedNode;
        int value = Convert.ToInt32(node.GetValue("ISEDIT"));
        int id = (int)node.GetValue("ID");
        int workerstate = Convert.ToInt32(grd_post.GetRowValues(grd_post.FocusedRowIndex, "CODE"));

        var query = (from m in regrar.MENURIGHT
                     where m.MENUID == id & m.WORKERSTATE == workerstate
                     select m).FirstOrDefault();
        if (query != null)
        {
            if (query.ISEDIT == 0)
            {
                query.ISEDIT = 1;
            }
            else
            {
                query.ISEDIT = 0;
            }
            regrar.SaveChanges();
        }
        //CreateTreeList();
        SetMenuVisible();
    }

    private void SetStateDelete()
    {
        TreeListNode node = TreeList.FocusedNode;
        int value = Convert.ToInt32(node.GetValue("ISDELETE"));
        int id = (int)node.GetValue("ID");
        int workerstate = Convert.ToInt32(grd_post.GetRowValues(grd_post.FocusedRowIndex, "CODE"));

        var query = (from m in regrar.MENURIGHT
                     where m.MENUID == id & m.WORKERSTATE == workerstate
                     select m).FirstOrDefault();
        if (query != null)
        {
            if (query.ISDELETE == 0)
            {
                query.ISDELETE = 1;
            }
            else
            {
                query.ISDELETE = 0;
            }
            regrar.SaveChanges();            
        }
        //CreateTreeList();
        SetMenuVisible();
    }

    private void SaveNodes()
    {
        int workerstate = Convert.ToInt32(grd_post.GetRowValues(grd_post.FocusedRowIndex, "CODE"));
        int parent = -1;
        foreach (var node in TreeList.GetAllNodes())
        {
            if (node.Selected == true && node.ParentNode.Selected == false)
            {
                int temp = Convert.ToInt32(node.ParentNode.GetValue("ID"));
                if (temp != parent && temp != 0)
                    MENURIGHT.SetMenuRight(regrar, workerstate, temp, node.Selected);
                parent = temp;
            }

            int id = Convert.ToInt32(node.GetValue("ID"));
            if (id != parent)
                MENURIGHT.SetMenuRight(regrar, workerstate, id, node.Selected);
        }

        regrar.SaveChanges();
        SetMenuVisible();
    }
}